import axios from "axios";
import {getCookie} from "~/utils/cookie";

// axios.defaults.withCredentials = true;
export enum WxtPageFields {
    '关键字推广' = 'adPv,click,charge,ctr,ecpc,ecpm,gmvInshopNum,gmvInshopAmt,prepayInshopAmt,prepayInshopNum,prepayDirAmt,prepayDirNum,prepayIndirAmt,prepayIndirNum,alipayDirAmt,alipayIndirAmt,alipayInshopAmt,alipayInshopNum,alipayDirNum,alipayIndirNum,cvr,roi,dirRoi,alipayInshopCost,cartInshopNum,cartDirNum,cartIndirNum,cartRate,itemColInshopNum,shopColDirNum,shopColInshopCost,colCartNum,colCartCost,itemColCart,itemColCartCost,colNum,itemColInshopCost,itemColInshopRate,cartCost,itemColDirNum,itemColIndirNum,couponShopNum,shoppingNum,shoppingAmt,wwNum',
    '精准人群推广' = 'adPv,click,charge,ctr,ecpc,ecpm,gmvInshopNum,gmvInshopAmt,prepayInshopAmt,prepayInshopNum,prepayDirAmt,prepayDirNum,prepayIndirAmt,prepayIndirNum,alipayDirAmt,alipayIndirAmt,alipayInshopAmt,alipayInshopNum,alipayDirNum,alipayIndirNum,cvr,roi,dirRoi,alipayInshopCost,cartInshopNum,cartDirNum,cartIndirNum,cartRate,itemColInshopNum,shopColDirNum,shopColInshopCost,colCartNum,colCartCost,itemColCart,itemColCartCost,colNum,itemColInshopCost,itemColInshopRate,cartCost,itemColDirNum,itemColIndirNum,couponShopNum,shoppingNum,shoppingAmt,wwNum,adUv,adUvCost,shopVisitUv,shopVisitUvCost,shopVisitUvRate,addNewUv,addNewUvAllCost,addNewUvUvRate,firstPurchaseUv,firstPurchaseUvCost,firstPurchaseUvRate,repurchaseUvCost,repurchaseUvRate',
    '消费者运营' = 'totalCharge,charge,adPv,click,ctr,ecpc,cartInshopNum,itemColInshopNum,colCartCost,prepayInshopNum,prepayInshopAmt,cvr,alipayInshopNum,alipayInshopAmt,roi,sampleAlipayInshopAmt,sampleAlipayInshopNum',
    '货品运营' = 'totalCharge,charge,adPv,click,ctr,ecpc,cartInshopNum,itemColInshopNum,colCartCost,cartDirNum,cartIndirNum,prepayInshopNum,prepayInshopAmt,cvr,alipayInshopNum,alipayInshopAmt,roi,alipayDirNum,alipayIndirNum,alipayDirAmt,alipayIndirAmt,noLAlipayInshopAmt,dirRoi',
    '活动场景' = 'totalCharge,charge,adPv,click,ctr,ecpc,ecpm,cartInshopNum,itemColInshopNum,colCartCost,cartDirNum,cartIndirNum,shopColDirNum,shopColInshopCost,colCartNum,prepayInshopNum,prepayInshopAmt,cvr,alipayInshopNum,alipayInshopAmt,roi,alipayDirNum,alipayIndirNum,alipayDirAmt,alipayIndirAmt,dirRoi',
    '内容营销' = 'liveViewNum,liveViewCost,charge,zbInteractCnt,avgZbInteractCnt,avgWatchDuration,favorNumber,shareNum,commentsNumber,followNumber,followNumberCost,inshopNum,feedInshopNumRate,itemColInshopNum,shoppingNum,shoppingAmt,cartInshopNum,alipayInshopAmt,alipayInshopNum,roi,alipayDirNum,alipayDirAmt,dirRoi,prepayInshopNum,prepayInshopAmt,addNewUv,addNewUvAllCost,addNewUvUvRate,firstPurchaseUv,firstPurchaseUvCost,firstPurchaseUvRate',
    '店铺运营' = 'totalCharge,charge,adPv,click,ctr,ecpc,ecpm,cartInshopNum,itemColInshopNum,colCartCost,cartDirNum,cartIndirNum,shopColDirNum,shopColInshopCost,colCartNum,prepayInshopNum,prepayInshopAmt,cvr,alipayInshopNum,alipayInshopAmt,roi,alipayDirNum,alipayIndirNum,alipayDirAmt,alipayIndirAmt,noLAlipayInshopAmt,dirRoi',
}

// 出价方式
export enum WxtBiddingMethods {
    '手动出价' = 'custom_bid',
    '最大化拿量' = 'max_amount',
    '控成本投放' = 'cost_control',
    '控投产比投放' = 'roi_control',
}

export enum WxtBiddingSmoothOptions {
    '标准投放' = 'quick',
    '智能均匀投放' = 'smooth',
}

// 预算类型 budgetList {dmcType: "unlimit", campaignId: "xxxx", dayBudget: undefined||number}
export enum WxtBiddingDmcType {
    '每日预算' = 'normal',
    '不限预算' = 'unlimit',
}

// 拿量目标 constraintType
export enum WxtBiddingConstraintType {
    '成交金额' = 'conv',     // 最大化拿量有
    '投产比' = 'roi',   // 只有控投产比投放才有
    '直接成交' = 'dir_conv',    // 只有控成本投放才有
    '促进成交' = 'conv',
    '促进直接成交' = 'ad_strategy_direct_buy',
    '促进全店成交' = 'ad_strategy_laxin',
    '收藏加购' = 'coll_cart',   // 只有控成本投放才有
    '宝贝点击' = 'click',       // 只有控成本投放才有
    '促进曝光' = 'exposure_pv',
    '提升新访客人数' = 'shop_visit_new',
    '提升兴趣新客人数' = 'shop_interest_new',
    '提升收购新客人数' = 'shop_purchase_new',
    '提升复购人数' = 'shop_repurchase',
    '人群资产转化' = 'high_cvr',
    '提升品牌互动人数' = 'deeplink_e2',
    '提升品牌行动人数' = 'deeplink_p',
    '提升品牌首购人数' = 'deeplink_i',
}

export enum WxtBizCode {
    '关键字推广' = 'onebpSearch',
    '精准人群推广' = 'onebpDisplay',
    '消费者运营-拉新快' = 'onebpAdStrategyDkx',
    '消费者运营-会员快' = 'onebpAdStrategyRuHui',
    '消费者运营-获客易' = 'onebpAdStrategyLiuZi',
    '消费者运营-粉丝快' = 'onebpAdStrategyFans',
    '货品运营-货品加速' = 'onebpAdStrategyProductSpeed',
    '货品运营-上新快' = 'onebpAdStrategyShangXin',
    '货品运营-测新快' = 'onebpAdStrategyCeKuan',
    '活动场景' = 'onebpAdStrategyYuRe',
    '内容营销' = 'onebpLive',
    '店铺运营' = 'onebpAdStrategyWholeShop',
    universalBP = 'universalBP',
}

export enum WxtTemplateType {
    // 地域
    AREA = 'AREA',
    // 时段
    PERIOD = 'PERIOD',
    // 'CROWD' = 'CROWD',
    // 'SHOP' = 'SHOP',
    // 'ITEM' = 'ITEM',
    // 'LIVE' = 'LIVE',
    // 'ACTIVITY' = 'ACTIVITY',
    // 'OTHER' = 'OTHER',
}

export class WxtUtils {
    static access: any = null;
    // 流量来源
    static adZonePkgIdList = [
        {
            id: '114790550289',
            title: '淘宝网搜索',
            desc: '计算机设备',
        },
        {
            id: '114790550288',
            title: '手机淘宝搜索',
            desc: '移动设备，含销量明星',
        },
        {
            id: '114793500012',
            title: '站外优质媒体',
            desc: '站外优质人群，推广种草必备',
        },
        {
            id: '114786650498',
            title: '搜索人群追投',
            desc: '搜索未转化人群在手淘信息流再触达',
        }
    ];
    static promotionGoalsList = [
        {
            id: 'shop_item',
            title: '全店宝贝推广',
        },
        {
            id: 'new_item_speed_car',
            title: '新品飞车',
        },
        {
            id: 'shop_crowd',
            title: '店铺人群运营',
        },
        {
            id: 'traffic_nd',
            title: '全屏微详情',
        }
    ];

    public static async getCookie(key: string) {
        return getCookie(key);
    }

    public static async getAccess() {
        if (!this.access) {
            let data = await axios.post(`https://one.alimama.com/member/checkAccess.json?bizCode=universalBP`, {
                bizCode: 'universalBP',
            }, {
                headers: {
                    'content-type': 'application/json;charset=UTF-8',
                },
                withCredentials: true,
            });
            this.access = data.data.data;
        }
        return this.access;
    }

    // 获取计划组
    public static async campaignGroupFindList(bizCode: WxtBizCode) {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        return axios.post(`https://one.alimama.com/campaignGroup/findList.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            bizCode: bizCode,
            csrfId,
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 获取主体
    public static async adgroupHorizontalFindPage(adzonePkgIdList: string[], startTime: string, endTime: string, bizCode: WxtBizCode, fields: WxtPageFields, offset: number = 0, pageSize: number = 100, effectEqual: undefined | number = undefined,extraData:any = {}) {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        // 判断startTime和endTime是否为一天并且为今天
        const today = new Date();
        const todayStr = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
        let isRt = false;
        if (startTime === endTime && startTime === todayStr) {
            isRt = true;
        }
        return axios.post(`https://one.alimama.com/adgroup/horizontal/findPage.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            csrfId,
            bizCode,
            offset,
            orderBy: '',
            orderField: '',
            pageSize,
            rptQuery: {
                conditionList: [
                    {
                        adzonePkgIdList,
                        startTime,
                        isRt,
                        endTime,
                    }
                ],
                fields: fields,
                effectEqual: undefined,
            },
            ...extraData,
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 获取计划
    public static async campaignHorizontalFindPage(adzonePkgIdList: string[], startTime: string, endTime: string, bizCode: WxtBizCode, fields: WxtPageFields, offset: number = 0, pageSize: number = 100, effectEqual: undefined | number = undefined) {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        // 判断startTime和endTime是否为一天并且为今天
        const today = new Date();
        const todayStr = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
        let isRt = false;
        if (startTime === endTime && startTime === todayStr) {
            isRt = true;
        }
        return axios.post(`https://one.alimama.com/campaign/horizontal/findPage.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            csrfId,
            bizCode,
            offset,
            orderBy: '',
            orderField: '',
            pageSize,
            rptQuery: {
                conditionList: [
                    {
                        adzonePkgIdList,
                        startTime,
                        isRt,
                        endTime,
                    }
                ],
                fields: fields,
                effectEqual: undefined,
            }
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 健康诊断
    public static async campaignFaultList(campaignIdList: string[], bizCode: WxtBizCode) {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        return axios.post(`https://one.alimama.com/diagnose/campaign/faultList.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            csrfId,
            bizCode,
            campaignIdList,
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 批量更新预算
    public static async campaignBudgetBatchUpdate(budgetList: {
        dmcType: string,
        campaignId: string,
        dayBudget: number | null,
        smoothOption: string | undefined
    }[], bizCode: WxtBizCode) {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        return axios.post(`https://one.alimama.com/campaign/budget/batchUpdate.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            csrfId,
            bizCode,
            budgetList,
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 批量更新出价
    public static async campaignBidBatchUpdate(bidList: {
        bidType: any | undefined,
        campaignId: number,
        constraintType: string | undefined,
        constraintValue: number | undefined
    }[], bizCode: WxtBizCode) {

        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        return axios.post(`https://one.alimama.com/campaign/bid/batchUpdate.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            csrfId,
            bizCode,
            bidList,
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 批量更新
    public static async advancedBatchUpdate(campaignList: any, bizCode: WxtBizCode) {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        return axios.post(`https://one.alimama.com/campaign/advanced/batchUpdate.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            csrfId,
            bizCode,
            campaignList,
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    public static async customFormRequest(url: string, bizCode: WxtBizCode, data: any = {}, isJsonString: boolean = true) {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        const _tb_token_ = await this.getCookie('_tb_token_');
        if (isJsonString) {
            // 把data转换成form-data 子项如果是对象则转换成json字符串
            Object.keys(data).map(key => {
                if (typeof data[key] === 'object') {
                    data[key] = JSON.stringify(data[key]);
                }
            });
        }
        return axios.post(`${url}?_tb_token_=${_tb_token_}&_csrf=${csrfId}&csrfId=${csrfId}`, {
            bizCode,
            ...data
        }, {
            headers: {
                // form-data
                'content-type': isJsonString ? 'application/x-www-form-urlencoded;charset=UTF-8' : 'application/json',
            },
            withCredentials: true,
        });
    }

    public static async customRequest(url: string, bizCode: WxtBizCode, data: any, params: any = {}) {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        let paramsStr = '';
        if (Object.keys(params).length > 0) {
            paramsStr = '&';
            // 把对象转换成字符串
            Object.keys(params).map(key => {
                paramsStr += `${key}=${params[key]}&`;
            });
            paramsStr = paramsStr.substring(0, paramsStr.length - 1);
        }
        return axios.post(url + `?csrfId=${csrfId}&bizCode=${bizCode}${paramsStr}`, {
            csrfId,
            bizCode,
            ...data
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 更新单个
    public static async campaignUpdatePart(campaignList: any, bizCode: WxtBizCode, extra: any = {}, type: string = 'campaign') {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        return axios.post(`https://one.alimama.com/${type}/updatePart.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            csrfId,
            bizCode,
            campaignList,
            ...extra
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 新增计划组
    public static async campaignGroupAdd(campaignGroupName: string, bizCode: WxtBizCode) {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        return axios.post(`https://one.alimama.com/campaignGroup/add.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            csrfId,
            bizCode,
            campaignGroupName,
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 批量设置计划组
    public static async campaignGroupUpdate(campaignGroupId: number, campaignIdList: string[], bizCode: WxtBizCode) {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        return axios.post(`https://one.alimama.com/campaign/updateGroup.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            csrfId,
            bizCode,
            campaignGroupId,
            campaignIdList,
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 建议日预算
    public static async algoGetBudgetSuggestion(bizCode: WxtBizCode, campaign: any) {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        return axios.post(`https://one.alimama.com/algo/getBudgetSuggestion.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            csrfId,
            bizCode,
            campaign,
            adgroupList: campaign.adgroupList,
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 报表查询
    public static async reportQuery(strategyCampaignIdIn: string[] | undefined, startTime: string, endTime: string, bizCode: WxtBizCode, queryFieldIn: string[], queryDomains: string[] = ['date', 'campaign'], source: string = 'baseReport', extra: any = {}) {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        let splitType = 'day';
        if (startTime === endTime) {
            splitType = 'date';
        }
        return axios.post(`https://one.alimama.com/report/query.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            csrfId,
            bizCode,
            startTime,
            endTime,
            queryDomains,
            queryFieldIn,
            source,
            splitType,
            strategyCampaignIdIn,
            fromRealTime: splitType == 'date' ? true : undefined,
            ...extra
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 操作日志
    public static async oplogFindList(startTime: string, endTime: string, bizCode: WxtBizCode, campaignIdList: string[] | undefined = undefined, offset: number = 0, pageSize: number = 40, entityTypeGroupCode = 'campaign', extra: any = {}) {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        // console.log(offset);
        return axios.post(`https://one.alimama.com/oplog/findList.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            bizCode,
            csrfId,
            campaignIdList,
            endTime,
            entityTypeGroupCode,
            offset,
            operationTypeGroupCode: "all",
            pageSize,
            startTime,
            ...extra
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 查询推荐模版
    public static async templateGetSuggest(bizCode: WxtBizCode, templateType: WxtTemplateType = WxtTemplateType.PERIOD, configType: string = 'DISCOUNT', bidType: string = 'custom_bid') {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        return axios.post(`https://bpcommon.alimama.com/template/getSuggest.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            bizCode: bizCode,
            csrfId,
            templateType,
            configType,
            bidType,
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 查询模板
    public static async templateFindList(templateType: WxtTemplateType, bizCode: WxtBizCode) {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        return axios.post(`https://bpcommon.alimama.com/template/findList.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            bizCode: bizCode,
            csrfId,
            templateType,
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    // 删除计划
    public static async deleteRecord(campaignIdList: any[] | undefined, bizCode: WxtBizCode, extra: any = {}, type: string = 'campaign') {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        return axios.post(`https://one.alimama.com/${type}/delete.json?csrfId=${csrfId}&bizCode=${bizCode}`, {
            bizCode: bizCode,
            csrfId,
            campaignIdList,
            ...extra
        }, {
            headers: {
                'content-type': 'application/json;charset=UTF-8',
            },
            withCredentials: true,
        });
    }

    public static async getAreaCodeConfig(bizCode: WxtBizCode): Promise<{
        name: string,
        id: number,
        provinceId: number,
        provinceName: string
    }[]> {
        const csrfId = (await this.getAccess())['accessInfo']['csrfId'];
        return new Promise((resolve, reject) => {
            axios.post(`https://bpcommon.alimama.com/commonapi/tetris/area/getCodeConfig.json?r=mx_1100`, {
                csrfId,
                templateType: 'AREA',
                bizCode,
            }, {
                headers: {
                    'content-type': 'application/json;charset=UTF-8',
                },
                withCredentials: true,
            }).then(res => {
                let areaCodeConfig: { name: string, id: number, provinceId: number, provinceName: string }[] = [];
                const keys = Object.keys(res.data.data);
                keys.forEach(key => {
                    const data = res.data.data[key];
                    data.forEach((item: any) => {
                        if (!item.provinces) {
                            areaCodeConfig.push({
                                name: item.name,
                                id: item.id,
                                provinceId: item.id,
                                provinceName: item.name,
                            });
                            return;
                        }
                        item.provinces.forEach((province: any) => {
                            if (!province.cities) {
                                areaCodeConfig.push({
                                    name: province.name,
                                    id: province.id,
                                    provinceId: province.id,
                                    provinceName: province.name,
                                });
                                return;
                            }
                            province.cities.forEach((city: any) => {
                                areaCodeConfig.push({
                                    name: city.name,
                                    id: city.id,
                                    provinceId: province.id,
                                    provinceName: province.name,
                                });
                            });
                        });
                    });
                })

                resolve(areaCodeConfig.concat(...[
                    {
                        name: '台湾',
                        id: 577,
                        provinceId: 577,
                        provinceName: '台湾',
                    },
                    {
                        name: '香港',
                        id: 599,
                        provinceId: 599,
                        provinceName: '香港',
                    },
                    {
                        name: '澳门',
                        id: 576,
                        provinceId: 576,
                        provinceName: '澳门',
                    },
                    {
                        name: '中国其他',
                        id: 531,
                        provinceId: 531,
                        provinceName: '中国其他',
                    },
                    {
                        name: '国外',
                        id: 574,
                        provinceId: 574,
                        provinceName: '国外',
                    }]));
            }).catch(err => {
                reject(err);
            });
        });

    }
}
